package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.entity.PageResult;
import com.itheima.mapper.PermissionMapper;
import com.itheima.pojo.Permission;
import com.itheima.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service(interfaceClass = PermissionService.class)
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public void add(Permission permission) {
        permissionMapper.add(permission);
    }

    /**
     * 查询所i有权限
     * @param currentPage
     * @param pageSize
     * @param queryString
     * @return
     */
    @Override
    public PageResult findAll(Integer currentPage, Integer pageSize, String queryString) {

        //使用分页插件分页
        PageHelper.startPage(currentPage, pageSize);
        //通过条件查询权限数据
        List<Permission> list = permissionMapper.findAll(queryString);
        PageInfo<Permission> pageInfo = new PageInfo<>(list);

        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 通过id查询权限
     * @param id
     * @return
     */
    @Override
    public Permission findById(Integer id) {

        return permissionMapper.findById(id);
    }

    /**
     *编辑权限
     * @param permission
     */
    @Override
    public void edit(Permission permission) {

        Integer count = findRoleAndPermission(permission.getId());
        if (count > 0) {
            throw new RuntimeException("该权限被引用，不能修改");
        } else {
            permissionMapper.edit(permission);
        }
    }

    public Integer findRoleAndPermission(Integer id) {
        return permissionMapper.findRoleAndPermission(id);
    }

    /**
     * 根据id删除权限
     * @param id
     */
    @Override
    public void delete(Integer id) {

        //查询该权限是否被引用
        Integer count = findRoleAndPermission(id);
        if (count > 0) {
            throw new RuntimeException("该权限被应用，不能删除");
        } else {
            permissionMapper.delete(id);
        }
    }

}
